import pygame

class Shop:
    def __init__(self, player, window, position):
        if not player:
            raise ValueError("Player cannot be None")
        if not window:
            raise ValueError("Window cannot be None")
        if not position:
            raise ValueError("Position cannot be None")
        
        self.player = player
        self.window = window
        self.position = position
        
        # 设置默认值，以防player对象没有这些属性
        self.player_max_health = getattr(player, 'max_health', 100)
        self.player_max_mana = getattr(player, 'max_mana', 100)
        
        self.items = [
            {'name': '生命药水', 'price': 25, 'type': 'health_potion', 'effect': 0.5 * self.player_max_health, 'image': 'assets/image/health.png'},
            {'name': '魔力药水', 'price': 25, 'type': 'mana_potion', 'effect': 0.3 * self.player_max_mana, 'image': 'assets/image/mana.png'},
            {'name': '武器', 'price': 30, 'type': 'weapon', 'effect': 10, 'image': 'assets/image/weapon.png'}
        ]
        self.font = pygame.font.SysFont(None, 24)
        self.fontcolor = (255, 255, 255)
        self.bgcolor = (0, 0, 0)
        self.dialogue_active = True
        self.npc_image = pygame.image.load('assets/Merchant/1.Merchant.png')  # 加载NPC商人的图像
        self.npc_image = pygame.transform.scale(self.npc_image, (150, 100))  # 调整图片大小
    
    def render_shop(self):
        self.window.fill(self.bgcolor)
        self.window.blit(self.npc_image, (self.position.x, self.position.y))  # 绘制NPC商人的图像
        offset = 0
        for item in self.items:
            text = self.font.render(f"{item['name']} - {item['price']}金币", True, self.fontcolor)
            self.window.blit(text, (self.position.x, self.position.y + offset + self.npc_image.get_height()))
            offset += self.font.get_height()
        pygame.display.flip()

    def buy_item(self, item):
        if self.player.gold >= item['price']:
            self.player.inventory.append(item)
            if item['type'] == 'weapon':
                self.player.attack_power += item['effect']
            elif item['type'] == 'health_potion':
                self.player.health = min(self.player.max_health, self.player.health + item['effect'])
            elif item['type'] == 'mana_potion':
                self.player.mana = min(self.player.max_mana, self.player.mana + item['effect'])
            self.player.gold -= item['price']
            print(f"购买了 {item['name']}，花费 {item['price']}金币")
        else:
            print("金币不足")

    def check_proximity(self):
        distance = self.player.pos.distance_to(self.position)
        if distance < 50:  # 如果玩家靠近商人
            self.dialogue_active = True  # 激活对话框

    def draw_dialogue(self):
        if self.dialogue_active:
            dialogue_text = self.font.render("欢迎！你需要什么？", True, self.fontcolor)
            self.window.blit(dialogue_text, (self.position.x, self.position.y - 50))
            pygame.display.flip()
